/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package persistence;

import database.DBConnection;
import java.util.ArrayList;
import java.util.HashMap;
import model.Event;

/**
 *
 * @author Martin Mohr Pedersen
 */
public class EventDAO {

    public Event getCurrentEvent() {
        String sql = "SELECT * FROM event ORDER BY start_time DESC LIMIT 1";

        return findOne(sql);
    }

    private Event findOne(String sql) {
        ArrayList<HashMap<String, Object>> results = DBConnection.getInstance().executeSelect(sql);
        
        return unpackOne(results);
    }

    private Event unpackOne(ArrayList<HashMap<String, Object>> results) {
        Event[] events = unpack(results);
        if (events.length > 0) {
            return events[0];
        } else {
            return null;
        }
    }

    private Event[] unpack(ArrayList<HashMap<String, Object>> results) {
        ArrayList<Event> events = new ArrayList<Event>();
        Event event;
        
        for (HashMap<String, Object> row : results) {
            event = new Event();

            java.sql.Timestamp endDate = (java.sql.Timestamp) row.get("end_time");
            event.setEndTime(new java.util.Date(endDate.getTime()));

            java.sql.Timestamp startDate = (java.sql.Timestamp) row.get("start_time");
            event.setStartTime(new java.util.Date(startDate.getTime()));

            event.setId(Integer.parseInt(row.get("id").toString()));
            event.setName(row.get("name").toString());

            events.add(event);
        }
        return events.toArray(new Event[events.size()]);
    }
}
